import 'dart:convert';

/// 音频模型
class Audio {
  final int audioId;
  final int articleId;
  final String language;
  final String? audioUrl;
  final String? duration;
  final String? fileSize;
  final String? fileMetadata;
  final List<TimestampItem>? timestamps;
  final String? status;
  final String? createTime;
  final String? updateTime;

  Audio({
    required this.audioId,
    required this.articleId,
    required this.language,
    this.audioUrl,
    this.duration,
    this.fileSize,
    this.fileMetadata,
    this.timestamps,
    this.status,
    this.createTime,
    this.updateTime,
  });

  factory Audio.fromJson(Map<String, dynamic> json) {
    List<TimestampItem>? timestampList;
    if (json['timestamps'] != null) {
      if (json['timestamps'] is String) {
        // 如果是字符串，需要先解析 JSON
        try {
          final dynamic parsed = jsonDecode(json['timestamps']);
          if (parsed is List) {
            timestampList = parsed
                .map((item) => TimestampItem.fromJson(item as Map<String, dynamic>))
                .toList();
          }
        } catch (e) {
          print('解析 timestamps 失败: $e');
          timestampList = null;
        }
      } else if (json['timestamps'] is List) {
        timestampList = (json['timestamps'] as List)
            .map((item) => TimestampItem.fromJson(item as Map<String, dynamic>))
            .toList();
      }
    }

    return Audio(
      audioId: json['audioId'] ?? 0,
      articleId: json['articleId'] ?? 0,
      language: json['language'] ?? 'cn',
      audioUrl: json['audioUrl'],
      duration: json['duration']?.toString(),
      fileSize: json['fileSize']?.toString(),
      fileMetadata: json['fileMetadata'],
      timestamps: timestampList,
      status: json['status'],
      createTime: json['createTime'],
      updateTime: json['updateTime'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'audioId': audioId,
      'articleId': articleId,
      'language': language,
      'audioUrl': audioUrl,
      'duration': duration,
      'fileSize': fileSize,
      'fileMetadata': fileMetadata,
      'timestamps': timestamps?.map((item) => item.toJson()).toList(),
      'status': status,
      'createTime': createTime,
      'updateTime': updateTime,
    };
  }
}

/// 时间戳模型（用于高亮句子）
class TimestampItem {
  final int index;
  final String text;
  final double start;
  final double end;

  TimestampItem({
    required this.index,
    required this.text,
    required this.start,
    required this.end,
  });

  factory TimestampItem.fromJson(Map<String, dynamic> json) {
    return TimestampItem(
      index: json['index'],
      text: json['text'] ?? '',
      start: (json['start'] ?? 0).toDouble(),
      end: (json['end'] ?? 0).toDouble(),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'index': index,
      'text': text,
      'start': start,
      'end': end,
    };
  }
}

